#!/usr/bin/env python
# coding=utf-8

import requests
# from bs4 import BeautifulSoup
import json
import re
import os
import thread

# 'ascii' codec can't encode characters
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def download_song_each(url, mp3Name):
    data = requests.get(url)

    mp3file = open(mp3Name, 'wb')
    mp3file.write(data.content)
    mp3file.close()

    print mp3Name

class BaiduMusicDownload(object):

    def __init__(self):
        self.__BASE_URL = r'http://music.baidu.com/search/song?s=1&key={author}&start={start}&size=20'
        self.__SONG_DATA_URL = r'http://music.baidu.com/data/music/fmlink?songIds='
        self.__SONG_SEARCH_URL = None
        self.__SONG_REAL_DATA = None
        self.__SONG_REAL_URL = None 

        # Song info
        self.__SONG_ID = None
        self.__SONG_NAME = None
        self.__SONG_AUTHOR = None
        self.__SONG_FORMAT = None
        self.__SONG_ALBUM = None

    def get_author_song_id(self, author, start):
        self.__SONG_SEARCH_URL = self.__BASE_URL.format(author=author, start=start)

        req = requests.get(self.__SONG_SEARCH_URL)
        song = req.content

        song_id_all = re.findall(r'<a href="/song/([^"]+)"', str(song))

        if len(song_id_all) == 0:
            return False
        
        self.__SONG_ID = song_id_all
        return song_id_all

    def get_real_song_data(self, song_id):
        data_url = self.__SONG_DATA_URL+str(song_id)
        req = requests.get(data_url)

        song_data = json.loads(str(req.content))['data']
        if song_data != '':
            songList = song_data['songList'][0]
            self.__SONG_NAME = songList['songName']
            self.__SONG_AUTHOR = songList['artistName']
            self.__SONG_FORMAT = songList['format']
            self.__SONG_ALBUM = songList['albumName']
            self.__SONG_REAL_URL = songList['songLink']
        
        self.__SONG_REAL_DATA = song_data
        return self.__SONG_REAL_DATA

            
    def download_song(self, author):
        if not os.path.exists(author):
            os.mkdir(author)
        os.chdir(author)

        start = 0
        while start < 60:
            self.get_author_song_id(author, start)
            for song_id in self.__SONG_ID:
                self.get_real_song_data(song_id)
               
                mp3Name = "{songName}--{author}.{format}".format(
                    songName = self.__SONG_NAME,
                    author = self.__SONG_AUTHOR,
                    format = self.__SONG_FORMAT,
                 )

                mp3Name = mp3Name.replace('/', '+')
                
                if os.path.isfile(mp3Name):
                    print "{0} 已存在..".format(mp3Name)
                    continue

                thread.start_new_thread(download_song_each, (self.__SONG_REAL_URL, mp3Name))
            start += 20

        os.chdir('..')

if __name__ == '__main__':
    import sys
    
    if len(sys.argv) == 1:
        print "Usage:"
        print "\t{filename} Artist".format(filename=sys.argv[0])
        print "\t{filename} Artist1 Artist2 ...".format(filename=sys.argv[0])
        exit(False)

    download = BaiduMusicDownload()
    for song in sys.argv:
        if song == sys.argv[0]:
            continue
        download.download_song(song)
